import asyncio
import os

from aiogram import Bot, Dispatcher
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiogram.fsm.storage.memory import MemoryStorage
from dotenv import load_dotenv, dotenv_values

from logs import SingletonLogger
from handlers.base_handlers import router as base_router

logger = SingletonLogger.get_instance(__name__).get_logger()

envs = dotenv_values(".env")


async def main(bot):
    try:
        logger.info("[START] Initializing")
        load_dotenv()
        logger.info("[_***_] Dotenv loaded")

        storage = MemoryStorage()
        logger.info("[_***_] Initialized storage")

        dp = Dispatcher(storage=storage)

        bot_info = await bot.get_me()
        logger.info(f"[_***_] Bot name: {bot_info.username}")

        dp.include_routers(
            base_router
        )

        # BOT START
        logger.info("[_***_] Starting bot polling")
        try:
            await asyncio.gather(
                dp.start_polling(bot),
                # send_broadcast(bot)
            )
        except KeyboardInterrupt:
            logger.info('Shutting down...')
    except Exception as e:
        logger.error(f"[BOT] Error: {e}")


if __name__ == '__main__':
    load_dotenv()
    bot = Bot(
        token=envs['BOT_TOKEN'],
        default=DefaultBotProperties(
            parse_mode=ParseMode.HTML
        )
    )
    try:
        asyncio.run(main(bot))
    except Exception as e:
        logger.error(f"[MAIN] Error: {e}")
